<?php
/**
 * 微信接口 处理微信关注 菜单点击 自动登录 发送消息
 */
namespace app\api\controller;


//use think\Db;
use think\Controller;
use think\Request;
use think\Db;
use app\api\model\WechatEvent;
use app\api\model\WechatMessage;
use wechat\component\WXBizMsgCrypt;



class Wechat extends Controller
{
    private $model = null;

    public function _initialize(){
        
    }

    /**
     * 微信第三方平台授权事件接收URL
     * 接收验证票据（component_verify_ticket），
     * 在第三方平台创建审核通过后，微信服务器会向其 ”授权事件接收URL” 每隔 10 分钟以 POST 的方式推送 component_verify_ticket
     */
    public function index()
    {
        $param = input('param.');
        $postData = \file_get_contents('php://input');
        
        $infoType = '';
        $authorizationCode = '';
        try{
            $xml_tree = new \DOMDocument();
            $mm = new WechatMessage;
            $msg = $mm->getDecryptWxMessage();

            if ($msg !== false) {
                $xml_tree->loadXML($msg);
                $infoType = $this->getXmlObjValue($xml_tree,'InfoType');
                $msgType = $this->getXmlObjValue($xml_tree,'MsgType');
                if(!empty($infoType)){
                    
                    if($infoType=='component_verify_ticket') {
                        $componentVerifyTicket = $this->getXmlObjValue($xml_tree,'ComponentVerifyTicket');
                        $createTime = $this->getXmlObjValue($xml_tree,'CreateTime');
                        $expired = date("Y-m-d H:i:s",$createTime+12*60*60);
                        Db::table('sy_wx_config')->where('wx_app_id="'.$mm->component_appid.'"')->update(['component_verify_ticket'=>$componentVerifyTicket,
                        'component_verify_ticket_expired'=>$expired]);
                    }
                    // 微信授权
                    if($infoType=='authorized'){
                        $appId = $this->getXmlObjValue($xml_tree,'AppId');
                        $authorizerAppid = $this->getXmlObjValue($xml_tree,'AuthorizerAppid');
                        // query auth code
                        $authorizationCode = $this->getXmlObjValue($xml_tree,'AuthorizationCode');
                        $authorizationCodeExpiredTime = $this->getXmlObjValue($xml_tree,'AuthorizationCodeExpiredTime');
                        $preAuthCode = $this->getXmlObjValue($xml_tree,'PreAuthCode');

                        $data = [];
                        $data['authorizer_appid'] = $authorizerAppid;
                        $data['authorization_code'] = $authorizationCode;
                        $data['authorization_code_expired'] = date("Y-m-d H:i:s",$authorizationCodeExpiredTime);
                        $data['pre_auth_code'] = $preAuthCode;
                        $data['authorized']  = 1;
                        // $data['authorizer_access_token'] = $authInfo['authorizer_access_token'];
                        // $data['authorizer_refresh_token'] = $authInfo['authorizer_refresh_token'];
                        // $data['func_info'] = json_encode($authInfo['func_info']);
                        // $data['expired'] = Db::raw('date_add(now(),INTERVAL '.$authInfo['expires_in'].' SECOND)');
                        $data['update_time'] = Db::raw('now()');
                        
                        $id = Db::table('sy_wx_auth_info')->where('authorizer_appid="'.$data['authorizer_appid'].'"')->value('id');
                        if($id){
                            Db::table('sy_wx_auth_info')->where('id='.$id)->update($data);
                        }
                        else{
                            Db::table('sy_wx_auth_info')->insert($data);
                        }
                    }

                    if($infoType=='unauthorized'){
                        $authorizerAppid = $this->getXmlObjValue($xml_tree,'AuthorizerAppid');
                        Db::table('sy_wx_auth_info')->where('authorizer_appid="'.$authorizerAppid.'"')->update(['authorized'=>2]);
                    }
                }
                
                subLog("解密后: " . $msg . "\n","decryptMsg");
            } 
        }
        catch(\Exception $e){
            subLog($e->getFile()." ".$e->getLine().":".$e->getMessage(),'oauth error','wechat');
        }
        subLog($param,'wx api','wechat');
        subLog($postData,'wx api input','wechat');
        subLog($infoType.' wechat index fisnished ,code:'.$authorizationCode,'-----','wechat');
        return 'success';
    }

    private function getXmlObjValue($xml_tree,$tag){
        $obj = $xml_tree->getElementsByTagName($tag);
        $value = null;
        if($obj->length>0){
            $value = $obj->item(0)->nodeValue;
        }
        return $value;
    }

    /**
     * 消息与事件接收URL
     * 第三方授权后，客户微信事件回调
     */
    public function messageEvent(){
        $em = new WechatEvent(false);
        $appId = input('param.appid');
        $param = input('param.');
        subLog($param,'messageEvent param','wechat');
        subLog(\file_get_contents('php://input'),'messageEvent postdata','wechat');
        if(empty($param['signature']) || empty($param['timestamp']) || empty($param['appid'])){
            subLog($param,'messageEvent not enough param','wechat');
            return show(400,'param not enough');
        }
        try{
            $wxReturn = $em->getDecryptWxReturn();
        }
        catch(\Exception $e){
            subLog($e->getMessage(),'decrypt exception','wechat');
            return show(0,'decrypt error');
        }
        // subLog($wxReturn,'messageEvent wxReturn','wechat');
        
        if(request()->method()=="GET"){
            if($em->checkSignature($param)){
                echo $param["echostr"];
            }
            else{
                echo $param["echostr"];
            }
            exit;
        }else{
            //验证消息真实性
            // $abc = $em->checkSignature($param);
            // $bcd = (String)$abc;
            // if($bcd != 1) exit;
            
            // 事件推送
            if($wxReturn->MsgType=='event'){
                // $em->doEvent();
            }
            // 普通消息
            else{
                $mm = new WechatMessage;
                $wxReturnArr = json_decode(json_encode($wxReturn),true);;
                // $msgId = $wxReturnArr['MsgId'];
                $toUserName = $wxReturnArr['ToUserName'];
                $openid = $wxReturnArr['FromUserName'];
                // subLog($appId,'wxreturn appid','wechat');
                $createTime = $wxReturnArr['CreateTime'];
                switch ($wxReturnArr['MsgType']){
                    case 'text':
                        $content = $wxReturnArr['Content'];
                        // 微信自动化测试的专用测试公众号
                        if($appId=='wx570bc396a51b8ff8' || $toUserName=='gh_3c884a361561'){
                            // $openid = 'gh_3c884a361561';
                            // $wxReturn->ToUserName = $toUserName;
                            // $wxReturn->FromUserName = $openid;
                            $appId= 'wx570bc396a51b8ff8';
                            subLog($content,'wxreturn content','wechat');
                            if($content=='TESTCOMPONENT_MSG_TYPE_TEXT'){
                                $mm->responseToWeixin($wxReturn, 'TESTCOMPONENT_MSG_TYPE_TEXT_callback');
                                return '';
                            }
                            else if(strpos($content,'QUERY_AUTH_CODE')>=0){
                                $mm->responseToWeixin($wxReturn, '');
                                
                                $query_auth_code = str_replace('QUERY_AUTH_CODE:','',$content);
                                // $query_auth_code = Db::table('sy_wx_auth_info')->where('authorizer_appid="'.$appId.'"')->value('authorization_code');
                                subLog($query_auth_code,'query_auth_code','wechat');
                                $getTokenResult = $mm->queryAuth($query_auth_code);
                                if($getTokenResult!==false) {
                                    $mm->accessToken = $getTokenResult['authorization_info']['authorizer_access_token'];
                                    $param =['content'=>$query_auth_code.'_from_api'];
                                    $sendResult = $mm->sendMsgToUser($openid,$param);
                                    subLog($sendResult,'sendResult','wechat');
                                }
                                else{
                                    // subLog($getTokenResult,'queryAuth failed','wechat');
                                }
                                return '';
                            }

                        }
                        
                    break;
                    case 'image':
                        $picUrl = $wxReturn->PicUrl;
                        $mediaId = $wxReturn->MediaId;
                    break;
                    case 'voice':
                        $mediaId = $wxReturn->MediaId;
                        $format = $wxReturn->Format;//语音格式，如amr，speex等
                    break;
                    case 'video':
                        $mediaId = $wxReturn->MediaId;//视频消息媒体id，可以调用获取临时素材接口拉取数据。
                        $thumbMediaId = $wxReturn->ThumbMediaId; //视频消息缩略图的媒体id，可以调用获取临时素材接口拉取数据。
                    break;
                        
                    case 'location':
                        $x = $wxReturn->Location_X;
                        $y = $wxReturn->Location_Y;
                        $scale = $wxReturn->Scale;
                        $label = $wxReturn->Label;
                    break;
                    case 'link':
                        $title = $wxReturn->Title;
                        $description = $wxReturn->Description;
                        $url = $wxReturn->Url;
                    default:
                    break;

                }

            }
            
        }
    }




}
